import django_filters
from django.db.models import Q
from . import models


# 过滤咖啡机
class ClientFilter(django_filters.FilterSet):
    key = django_filters.CharFilter(help_text="行业", label="行业", method="filter_key")
    lon = django_filters.CharFilter(help_text="经度", label="经度", method="filter_lon")
    lat = django_filters.CharFilter(help_text="维度", label="维度", method="filter_lat")

    def filter_lon(self, queryset, name, value):
        # if value:
        #     value = float(value)
        # else:
        return queryset

    def filter_lat(self, queryset, name, value):
        # if value:
        #     value = float(value)
        # else:
        return queryset

    def filter_key(self, queryset, name, value):
        if value == "all":
            return queryset
        else:
            return queryset.filter(channel__trade__key=value)

    class Meta:
        model = models.CoffeeClient
        fields = ("key",)


# 过滤券
class CouponInfoFilter(django_filters.FilterSet):
    c_type = django_filters.ChoiceFilter(help_text="类型", choices=models.CouponInfo.cType, label="类型")
    expired = django_filters.BooleanFilter(help_text="是否过期", label="是否过期")
    used = django_filters.BooleanFilter(help_text="是否使用", label="是否使用")

    class Meta:
        model = models.CouponInfo
        fields = ("c_type", "expired", "used")


class GiveRecordFilter(django_filters.FilterSet):
    giveType = ((1, "收到"), (2, "赠出"), (3, "退回"))
    give_type = django_filters.ChoiceFilter(method="filter_give_type", label="收到/赠出", choices=giveType)

    def filter_give_type(self, queryset, name, value):
        user = self.request.user
        if value == 1 or value == "1":
            return queryset.filter(receive_user=user)
        elif value == 2 or value == "2":
            return queryset.filter(own_user=user).exclude(status=3)
        else:
            return queryset.filter(own_user=user).filter(status=3)

    class Meta:
        model = models.GiveRecord
        fields = ("give_type",)


# 订单过滤
class OrdersFilter(django_filters.FilterSet):
    result = django_filters.ChoiceFilter(method="filter_result", label="状态", choices=models.CoffeeOrder.orderStatus)
    invoicable = django_filters.ChoiceFilter(method="filter_invoicable", label="是否可以开发票",
                                             choices=((1, "可以开发票的订单"), (0, "不可以开发票的订单")))

    def filter_result(self, queryset, name, value):
        if value == 2:
            return queryset.filter(Q(result=2) | Q(result=3))  # 已完成的里边包含支付成共和取消订单的
        else:
            return queryset.filter(result=value)

    def filter_invoicable(self, queryset, name, value):
        if value:
            return queryset.filter(invoiced=0, result=1).exclude(payment=0)
        else:
            return queryset

    class Meta:
        model = models.CoffeeOrder
        fields = ("result",)


# 优惠券使用
class UseFilter(django_filters.FilterSet):
    status = django_filters.ChoiceFilter(help_text="使用状态", choices=models.UseRecord.Status, label="使用状态")

    class Meta:
        model = models.UseRecord
        fields = ("status",)


# 券数量列表 过滤来源
class CouponSourceFilter(django_filters.FilterSet):
    # 什么没有的时候是点击【优惠券赠送】时显示的
    Source = ((1, "orders"), (2, "counts"))  # 1、counts是我的里面的，2、orders是提交订单时
    source = django_filters.ChoiceFilter(help_text="来源", choices=Source, label="来源", method="filter_source")
    vmc = django_filters.CharFilter(help_text="机器码", label="机器码", method="filter_vmc")
    valid = django_filters.NumberFilter(help_text="有效的", label="有效的", method="filter_valid")
    c_type = django_filters.NumberFilter(help_text="券类型", label="券类型", method="filter_c_type")

    class Meta:
        model = models.CouponInfo
        fields = ("source", "vmc", "valid", "c_type")

    def filter_valid(self, queryset, name, value):
        return queryset

    def filter_c_type(self, queryset, name, value):
        return queryset

    def filter_source(self, queryset, name, value):
        value = self.request.query_params.get("source")
        if value == 2 or value == "2":
            pass
        elif value == 1 or value == "1":
            queryset = queryset.filter(status=1)
        else:
            queryset = queryset.filter(can_share=True)
        return queryset

    def filter_vmc(self, queryset, name, value):
        c_type = self.request.query_params.get("c_type")  # 1 免费券A
        if self.request.query_params.get("valid") == 1 or self.request.query_params.get("valid") == "1":  # 有效的
            if value:
                coffee_client = models.CoffeeClient.objects.get(sign=value)
                channel = coffee_client.channel
                # 找到当前的渠道和通用券（is_special = False）
                if c_type:
                    if c_type == 1 or c_type == "1":  # 如果选择的是免费券A 选择免费券A
                        # 查找有效的，免费券A，并且可以在此渠道使用
                        # 查找此渠道的券，或者is_special = False
                        queryset = queryset.filter(Q(channel=channel) | Q(is_special=False), Q(c_type=1))
                    elif c_type == 6 or c_type == "6":  # 选择免费券B
                        queryset = queryset.filter(Q(channel=channel) | Q(is_special=False), Q(c_type=6))
                    else:  # 如果没有选择c_type 那么只去除此渠道就行
                        queryset = queryset.filter(Q(channel=channel) | Q(is_special=False))
                else:
                    queryset = queryset.filter(Q(is_special=False) | Q(channel=channel))
                return queryset
            else:
                return queryset
        # 无效的(去除此渠道的码)
        elif self.request.query_params.get("valid") == 0 or self.request.query_params.get("valid") == "0":
            if value:
                coffee_client = models.CoffeeClient.objects.get(sign=value)
                channel = coffee_client.channel
                # 找到当前的渠道和通用券（is_special = False）
                if c_type:  # 如果是无效的，那么需要判断c_type 1:免费券A 6 免费券B
                    # 当前是无效的，所以要查找不是此渠道的，并且is_special=True，或者c_type不是免费券A
                    if c_type == 1 or c_type == "1":  # 如果选择的是免费券A 那么就要除了此渠道的码 还需要除去免费券B
                        queryset = queryset.filter(Q(~Q(channel=channel), Q(is_special=True)) | ~Q(c_type=6))
                    elif c_type == 6 or c_type == "6":  # 如果选择的是免费券B 那么就要除了此渠道的码 还需要除去免费券A
                        queryset = queryset.filter(Q(~Q(channel=channel), Q(is_special=True)) | ~Q(c_type=1))
                        # queryset = queryset.filter(~Q(channel=channel),~Q(c_type=1))
                    else:  # 如果没有选择c_type 那么只去除此渠道就行
                        queryset = queryset.filter(~Q(channel=channel), Q(is_special=True))
                else:
                    queryset = queryset.filter(~Q(channel=channel), Q(is_special=True))
                return queryset
            else:
                return queryset
        else:
            return queryset


# 卡包订单
class CardBagOrdersFilter(django_filters.FilterSet):
    class Meta:
        model = models.CardBagOrders
        fields = ("result",)


class CoffeeTypeFilter(django_filters.FilterSet):
    c_type = django_filters.ChoiceFilter(help_text="来源", choices=models.Coffee.coffeeType, label="coffee 类型")


class CardBagRecordFilter(django_filters.FilterSet):
    giveType = ((1, "收到"), (2, "赠出"), (3, "退回"))
    give_type = django_filters.ChoiceFilter(method="filter_give_type", label="收到/赠出", choices=giveType)

    def filter_give_type(self, queryset, name, value):
        user = self.request.user
        if value == 1 or value == "1":
            return queryset.filter(receive_user=user.id)
        elif value == 2 or value == "2":
            return queryset.filter(own_user=user.id).exclude(status=3)
        else:
            return queryset.filter(own_user=user.id).filter(status=3)

    class Meta:
        model = models.CardBagRecord
        fields = ("give_type",)


class UserCardBagFilter(django_filters.FilterSet):
    bag_status = django_filters.ChoiceFilter(label="收到/赠出", choices=models.UserCardBag.bagStatus)

    class Meta:
        model = models.UserCardBag
        fields = ("bag_status",)


class UserCardFoldBagFilter(django_filters.FilterSet):
    card_type = django_filters.ChoiceFilter(label="98/198", choices=models.CardBag.cardType, method="filter_c_type")

    def filter_c_type(self, queryset, name, value):
        if value:
            return queryset.filter(cardbag__card_type=value)
        else:
            return queryset

    class Meta:
        model = models.UserCardBag
        fields = ("card_type",)


class ShopInfoFilter(django_filters.FilterSet):
    h5_active_id = django_filters.NumberFilter(label="活动id", method="filter_h5_active_id")

    def filter_h5_active_id(self, queryset, name, value):
        return queryset.filter(h5_active_id=value)

    class Meta:
        model = models.ShopInfo
        fields = ("h5_active_id",)


class GroupQRCodeClientFilter(django_filters.FilterSet):
    lon = django_filters.CharFilter(help_text="经度", label="经度", method="filter_lon")
    lat = django_filters.CharFilter(help_text="维度", label="维度", method="filter_lat")
    address = django_filters.CharFilter(help_text="地址过滤", label="地址过滤", lookup_expr="contains")
    city = django_filters.CharFilter(help_text="城市", label="city")

    def filter_lon(self, queryset, name, value):
        return queryset

    def filter_lat(self, queryset, name, value):
        return queryset

    class Meta:
        model = models.CoffeeClient
        fields = ("lon", "lat", "address", "city")


class PayTitleFilter(django_filters.FilterSet):
    orderNo = django_filters.CharFilter(help_text="订单编号", label="订单编号", method="filter_orderNo")
    def filter_orderNo(self, queryset, name, value):
        if value:
            instance = models.CoffeeOrder.objects.filter(orderNo=value).first()
            if instance:
                queryset = queryset.filter(client_id=instance.coffee_client.sign)
            else:
                queryset = models.PayTitle.objects.none()
        else:
            queryset = models.PayTitle.objects.none()
        return queryset


    class Meta:
        model = models.PayTitle
        fields = ("orderNo", )
